import { PageConfig } from 'next';
import anylogger from 'anylogger';
import '@mmstudio/an000042';
import an48 from '@mmstudio/an000048';
import { tbdict } from '../../../../atoms/db';

const logger = anylogger('pages/api/admin/dictsys/edit.api');

export type Result = {
	ok: true;
} | {
	ok: false;
	message: string;
};

export type Message = {
	type: string;
	name: string;
	key: number;
	value: string;
	key_c: number;
	type_c: string;
}

/**
 * 值列维护修改服务
 */
const handler = an48<Result>();

handler.post(async (req, res) => {
	try {
		logger.debug('msg body:', req.body);
		const { key, type, key_c, type_c, ...body } = req.body as Message;
		//检测参数
		if (!type) {
			res.status(200).json({
				ok: false,
				message: '类型不能为空，请填写完整'
			});
			return;
		}
		if (!body.name) {
			res.status(200).json({
				ok: false,
				message: '名称不能为空，请填写完整'
			});
			return;
		}
		if (!key) {
			res.status(200).json({
				ok: false,
				message: '键不能为空，请填写完整'
			});
			return;
		}
		if (!body.value) {
			res.status(200).json({
				ok: false,
				message: '值不能为空，请填写完整'
			});
			return;
		}
		//检查是否存在
		if (key_c != key || type_c != type) {
			const user = await tbdict().first('*').where({
				key, type
			});
			if (user) {
				res.status(200).json({
					ok: false,
					message: '已存在！'
				});
				return;
			}
		}
		//修改
		await tbdict().update({ key, type, ...body }).where({
			key: key_c, type: type_c
		});

		res.status(200).json({ ok: true });
	} catch (error) {
		logger.trace(error);
		res.status(200).json({ ok: false, message: (error as Error).message });
	}
});

export const config = {} as PageConfig;

export default handler;
